#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>

const std::string gpath = "/home/zxw/linux_-ubuntu/class/lesson4";
int gprojID = 0x66666;
int gshmsize = 4096;
mode_t gmod = 0600;

std::string ToHex(key_t k)
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer), "0x%x", k); // %x表示输出16进制
    return buffer;
}

class ShareMemory
{
private:
    void CreateShmHelper(int shmflag)
    {
        key_t _key = ftok(gpath.c_str(), gprojID);
        if (_key < 0)
        {
            std::cerr << "ftok error" << std::endl;
            return ;
        }
        _shmid = ::shmget(_key, gshmsize, shmflag);
        if (_shmid < 0)
        {
            std::cerr << "shmget error" << std::endl;
            return;
        }
        std::cout << "shmid: " << _shmid << std::endl;
    }
public:
    ShareMemory()
    :_shmid(-1)
    ,_key(0)
    ,_addr(nullptr)
    {}
    ~ShareMemory(){}
    void CreateShm()
    {
        CreateShmHelper(IPC_CREAT | IPC_EXCL | gmod);
    }
    // 创建共享内存 && 获取
    void GetShm()
    {
        CreateShmHelper(IPC_CREAT);
    }
    // 挂接
    void AttachShm()
    {
        _addr = shmat(_shmid,nullptr,0); 
        if((long long)_addr == -1)
        {
            std::cout << "attach error" << std::endl;
        }
    }
    // 取消挂接
    void DetachShm()
    {
         ::shmdt(_addr);
         std::cout << "detach done" << std::endl;
    }
    // 删除
    void DeleteShm()
    {
        shmctl(_shmid, IPC_RMID, nullptr);
    }

    void ShmMeta()
    {
    }

    int Getshmid()
    {
        return _shmid;
    }
    key_t Getkey()
    {
        return _key;
    }
    void* Getaddr()
    {
        return _addr;
    }
private:
    int _shmid;
    key_t _key;
    void* _addr;
};

ShareMemory shm;

struct data
{
    char status[32];
    char lasttime[48];
    char image[4000];
};